package com.mrdeer.web.controller.sys;

import cn.hutool.http.HtmlUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mrdeer.common.JSONResult;
import com.mrdeer.common.constants.CommonConstant;
import com.mrdeer.common.entity.dto.MessageDTO;
import com.mrdeer.common.entity.sys.Message;
import com.mrdeer.common.entity.sys.MessageSend;
import com.mrdeer.common.entity.sys.User;
import com.mrdeer.web.service.sys.SysMessageSendService;
import com.mrdeer.web.service.sys.SysMessageService;
import com.mrdeer.web.service.sys.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@Api(tags = "消息内容管理接口")
@RequestMapping("/mrdeer/message")
@Transactional
public class SysMessageController {

    @Resource
    private SysMessageService sysMessageService;

    @Resource
    private SysMessageSendService sysMessageSendService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SimpMessagingTemplate simpMessagingTemplate;

    @RequestMapping(value = "/getMessageByCondition", method = RequestMethod.POST)
    @ApiOperation(value = "多条件分页获取")
    public JSONResult getByCondition(@RequestBody MessageDTO message) {
        try {
            Page<Message> page = sysMessageService.list(message);
            return JSONResult.ok(page);
        } catch (Exception e) {
            return JSONResult.errorMsg("" + e.getMessage());
        }
    }

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "通过id获取")
    public JSONResult get(@PathVariable String id) {
        Message message = sysMessageService.getById(id);
        message.setContentText(HtmlUtil.filter(message.getContent()));
        return JSONResult.ok(message);
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加消息")
    public JSONResult addMessage(Message message) {
        sysMessageService.save(message);
        Message m = sysMessageService.getOne(new LambdaQueryWrapper<Message>().eq(Message::getTitle, message.getTitle()));
        //保存消息发送表
        List<MessageSend> messageSends = new ArrayList<>();
        if (CommonConstant.MESSAGE_RANGE_ALL.equals(message.getRange())) {
            //发送消息给全体
            List<User> allUser = sysUserService.list();
            allUser.forEach(u -> {
                MessageSend ms = new MessageSend().setMessageId(m.getId()).setUserId(u.getId());
                messageSends.add(ms);
            });
            sysMessageSendService.saveOrUpdateBatch(messageSends);
            //推送
            simpMessagingTemplate.convertAndSend("/topic/subscribe", "您收到了新的系统消息");
        } else {
            //指定用户
            for (String id : message.getUserIds().split(",")) {
                MessageSend ms = new MessageSend().setMessageId(m.getId()).setUserId(id);
                messageSends.add(ms);
            }
            sysMessageSendService.saveOrUpdateBatch(messageSends);
            //推送
            for (String id : message.getUserIds().split(",")) {
                simpMessagingTemplate.convertAndSendToUser(id, "/queue/subscribe", "您收到了新的消息");
            }
        }
        return JSONResult.ok("添加成功");
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ApiOperation(value = "编辑消息")
    public JSONResult editMessage(@RequestBody Message message) {
        sysMessageService.update(message, new LambdaQueryWrapper<Message>().eq(Message::getId, message.getId()));
        return JSONResult.ok("编辑成功");
    }

    @RequestMapping(value = "/delByIds", method = RequestMethod.POST)
    @ApiOperation(value = "删除消息")
    public JSONResult delMessage(@RequestParam String ids) {
        String[] idArr = ids.split(",");
        for (String id : idArr) {
            //TODO:工作流相关消息无法删除
            sysMessageService.removeById(id);
            //删除发送表
            sysMessageSendService.deleteByMessageId(id);
        }
        return JSONResult.ok("删除成功");
    }
}
